import java.net.URL;

class PageFetcher extends Thread {
	TweetsFetcher tweetFetcher;
	Object hasJob;
	
	public PageFetcher(TweetsFetcher tweetFetcher) {
		this.tweetFetcher = tweetFetcher;
		this.hasJob = tweetFetcher.hasJob;
	}

	@Override
	public void run() {
		boolean kill = false;
		while(!kill) {
			// Wait for Jobs
			synchronized(hasJob) {
				try {
					while(!tweetFetcher.hasPageToLoad()) {
						hasJob.wait(1000);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			tweetFetcher.increaseWorkingKids();

			URL url = tweetFetcher.getPageURL();
			while(url != null) {				
				Downloader downloader = new Downloader(url);
				String xml = downloader.fetchAsString();
				tweetFetcher.handlePageResults(xml);
				
				// Stop if there are a lot of kids
				if(tweetFetcher.shouldKillSomeKids()) {
					// System.err.println("stopped");
					kill = true;
					break;
				}
				
				url = tweetFetcher.getPageURL();
			}
			
			tweetFetcher.decreaseWorkingKids();
		}
	}
}